<template>
  <div class="com-container">
    <FDHeader></FDHeader>
    <!-- 表单设计-->
    <main class="com-page">
        <div class="fd">
            <header class="inline-center com-layout-top">
                <a class="com-btn btn-primary-reversal" href="javascript:;"><i class="iconfont icon-dayin1"></i>打印</a>
                <a class="com-btn btn-primary-reversal" href="javascript:;"><i
                        class="iconfont icon-yulanceshi"></i>预览</a>
                <a class="com-btn btn-primary-reversal" href="javascript:;"><i class="iconfont icon-zhongzhi"></i>重置</a>
                <a class="com-btn btn-primary-reversal" href="javascript:;"><i class="iconfont icon-save"></i>保存</a>
                <a class="com-btn btn-primary fr" href="javascript:;">发布</a>
            </header>
            <div class="com-layout">
                <FDPanel></FDPanel>
                <aside class="com-panel panel-center">
                    <header class="panel-tit">
                        <span class="fl">这是个标题</span>
                        <span class="fr">当前版本：V1.0.0</span>
                    </header>
                    <div class="panel-content">
                        <section class="view">
                            <!-- 默认-->
                            <div class="default-main">
                                <i class="default-ico"></i>

                                <p>请从左侧拖动控件创建属于你的表单</p>
                            </div>
                            <div class="widgetPull ui-sortable">

                            </div>

                        </section>
                    </div>
                    <footer class="panel-footer">
                        <a class="com-btn btn-primary fr" href="javascript:;">提交</a>
                    </footer>
                </aside>
                <aside class="com-panel panel-right com-tab">
                    <header class="panel-tit">
                        <ul class="tab-tit tab-half tab-header">
                            <li class="on">控件设置</li>
                            <li>表单设置</li>
                        </ul>
                    </header>
                    <div class="panel-content tab-content">
                        <section class="content forms-content on">
                            <setting-layout v-if="settingTarget === 'form-layouts'"></setting-layout>
                            <setting-input v-if="settingTarget === 'form-formLine'"></setting-input>
                            <setting-textarea v-if="settingTarget === 'form-mutipleLine'"></setting-textarea>
                            <setting-numberinput v-if="settingTarget === 'form-mutipleLine'"></setting-numberinput>
                            <setting-description v-if="settingTarget === 'form-describe'"></setting-description>
                            <setting-radio v-if="settingTarget === 'form-radio'"></setting-radio>
                            <setting-checkbox v-if="settingTarget === 'form-check'"></setting-checkbox>
                            <setting-select v-if="settingTarget === 'form-droplist'"></setting-select>
                            <!-- 时间区间-->
                            <form class="form form-time ">
                                <!--#include virtual="/include/form/view/_form-标题.shtml" -->
                                <!--#include virtual="/include/form/view/_form-时间区间-时间格式.shtml" -->
                                <!--#include virtual="/include/form/view/_form-默认值-下拉.shtml" -->
                                <!--#include virtual="/include/form/view/_form-提示.shtml" -->
                                <!--#include virtual="/include/form/view/_form-时间区间-校验.shtml" -->
                                <!--#include virtual="/include/form/view/_form-布局设置-排列.shtml" -->
                                <!--#include virtual="/include/form/view/_form-时间区间-其他设置.shtml" -->
                            </form>
                            <!--图片 -->
                            <form class="form form-pic ">
                                <!--#include virtual="/include/form/view/_form-标题.shtml" -->
                                <!--#include virtual="/include/form/view/_form-提示.shtml" -->
                                <!--#include virtual="/include/form/view/_form-图片-上传方式.shtml" -->
                                <!--#include virtual="/include/form/view/_form-图片-校验.shtml" -->
                                <!--#include virtual="/include/form/view/_form-图片-其他设置.shtml" -->
                            </form>

                            <!-- 人员选择-->
                            <form class="form form-staff ">
                                <!--#include virtual="/include/form/view/_form-标题.shtml" -->
                                <!--#include virtual="/include/form/view/_form-人员选择默认.shtml" -->
                                <!--#include virtual="/include/form/view/_form-人员选择-校验.shtml" -->
                                <!--#include virtual="/include/form/view/_form-布局设置-排列.shtml" -->
                                <!--#include virtual="/include/form/view/_form-其他设置.shtml" -->
                            </form>
                            <!-- 按钮 -->
                            <form class="form form-btn ">
                                <!--#include virtual="/include/form/view/_form-按钮事件.shtml" -->
                                <!--#include virtual="/include/form/view/_form-按钮文字内容.shtml" -->
                                <!--#include virtual="/include/form/view/_form-按钮样式.shtml" -->
                                <!--#include virtual="/include/form/view/_form-按钮布局.shtml" -->
                                <!--#include virtual="/include/form/view/_form-隐藏.shtml" -->
                                <!-- <a data-modal=".ui-btn-modal" href="javascript:;">跳转设置</a> -->
                            </form>

                        </section>

                        <section class="content ">
                            <!--#include virtual="/include/form/_formSet.shtml" -->
                        </section>

                    </div>
                </aside>
            </div>

        </div>
    </main>
    <!-- /表单设计-->
    <!-- 确认删除弹窗-->
    <!--#include virtual="include/_pop-affirm.shtml" -->
    <!-- 人员选择弹窗-->
    <!--#include virtual="ui/staff/_staff-model.shtml" -->
    <!-- 跳转设置弹窗-->
    <!--#include virtual="include/form/_btn-model.shtml" -->
</div>
</template>

<script>
import FDHeader from "./FDHeader.vue";
import FDPanel from "./FDPanel.vue";
import settingLayout from "./setting/setting-layout.vue";
import settingInput from "./setting/setting-input.vue";
import settingTextarea from "./setting/setting-textarea.vue";
import settingNumberinput from "./setting/setting-numberinput.vue";
import settingDescription from "./setting/setting-description.vue";
import settingRadio from "./setting/setting-radio.vue";
import settingCheckbox from "./setting/setting-checkbox.vue";
import settingSelect from "./setting/setting-select.vue";
import "@/assets/js/libs/jquery/jquery-1.8.3.min";
import "@/assets/js/libs/jquery/jquery-throttle-debounce.min";
import "@/assets/js/libs/jquery/common";
import "@/assets/js/libs/jquery/jquery-ui";
import { mapState, mapMutations } from "vuex";
export default {
  data() {
    return {
      title: "",
      widgetId: 1,
      currWidgetId: "",
      settingTarget: ""
    };
  },

  components: {
    FDHeader,
    FDPanel,
    settingLayout,
    settingInput,
    settingTextarea,
    settingNumberinput,
    settingDescription,
    settingRadio,
    settingCheckbox,
    settingSelect
  },

  mounted() {
    let _this = this;
    (function() {
      var $defaultview = $(".default-main"),
        $widgetPull = $(".widgetPull"),
        $msgbox = $(".ui-msgbox"),
        $mxRowFrom,
        $forms = $(".forms-content");

      /**
     * 控件设置表单切换
     * @param target jquery选择器
     */
    //   function changeForm(target) {
    //     $(target, $forms)
    //       .addClass("on")
    //       .siblings()
    //       .removeClass("on");
    //   }

      $forms.on("click", ".icon-yincang", function(e) {
        $(e.target).toggleClass("close");
      });
      //关闭弹窗
      $msgbox.on("click", ".msgbox-close", function() {
        $msgbox.removeClass("open");
      });
      $(".form-section").each(function() {
        var $this = $(this),
          $link = $(".section-link", $this),
          $close = $(".close", $this),
          $main = $(".section-main", $this);
        $link.on("click", function(e) {
          $(".section-main").removeClass("on");
          $main
            .css({
              top: $link.offset().top + 30,
              right: $(window).width() - $link.offset().left - 70
            })
            .addClass("on");
          return false;
        });
        $close.on("click", function() {
          $main.removeClass("on");
        });
      });

      $widgetPull
        .on("click", ".ico-close", function(e) {
          //点击删除，打开删除组件确认弹窗
          e.stopPropagation();
          $msgbox.addClass("open");
          return false;
        })
        .on("click", ".ui-draggable", function(e) {
          //点击组件 切换控件中的表单
          e.stopPropagation();
        //   var target =
        //     "." +
        //     $(e.target)
        //       .parents(".ui-draggable")
        //       .attr("data-target");
        //   changeForm($(this).attr('data-target'));
          _this.settingTarget = $(this).attr('data-target')
          _this.settingId($(this).attr("id"));
          let params = {
                id: $(this).attr("id"),
                title: $(this).find('label').eq(0).text(),
                description: $(this).find('.info').eq(0).text()
            }

            if (_this.settingTarget === 'form-formLine') {
                params.defaultVal = $(this).find('input[type="text"]').val()
            }

            _this.saveSetting(params)
        })
        .on("click", ".ico-moveTop", function(e) {
          //元素上移合并
          e.stopPropagation();
          var $current = $(e.target).parents(".ui-draggable"),
            $prev = $current.prev(),
            $next = $current.next(),
            $items = $('<div class="items"></div>');
          if (!$prev.hasClass("items")) {
            $prev.addClass("half").appendTo($items);
            $current.addClass("half").appendTo($items);
            if ($next.length == 1) {
              $items.insertBefore($next);
            } else {
              $items.appendTo($widgetPull);
            }
            $items.sortable({
              placeholder: "item-highlight",
              cursor: "move",
              items: ".half"
            });
          }
          return false;
        })
        .on("click", ".ico-moveDown", function(e) {
          //元素下移动，解除合并
          e.stopPropagation();
          var $current = $(e.target).parents(".ui-draggable"),
            $items = $current.parents(".items"),
            $brother = $current.siblings();
          $current.insertAfter($items).removeClass("half");
          $brother.insertAfter($items).removeClass("half");
          $items.remove();
          return false;
        })
        .on("click", ".ico-moveChange", function(e) {
          //左右交换
          e.stopPropagation();
          var $current = $(e.target).parents(".ui-draggable"),
            $brother = $current.siblings(),
            index = $current.index();
          if (index == 0) {
            $current.insertAfter($brother);
          } else {
            $brother.insertAfter($current);
          }
          return false;
        });

      /**
     * 布局组件拖放时，比较最高高度，设置为空间列最高高度
     * @param $target 组件被放置的布局对象
     */
      function maxHeight($target) {
        var $current = $target.parents(".ly-it"),
          $ly;
        $ly = $current.length == 0 ? $mxRowFrom : $target.parents(".ly-row");
        if ($ly && $ly.length == 1) {
          $ly.css({ height: "auto" }).height($ly.height());
        }
      }

      //明细控件
      $.fn.mxly = function(options) {
        var defaults = {
          container: $widgetPull,
          addHandel: ".hd-add",
          dragHandel: ".hd-drag",
          delHandel: ".hd-del",
          delColHandel: ".hd-del-col",
          editHandel: ".hd-edit"
        };
        var settings = $.extend({}, defaults, options);

        /**
         * 添加列的可拖放操作
         * @param $target
         */
        function dropable($target) {
          $target
            .droppable({
              accept: ".widgetForm .item"
            })
            .sortable({
              connectWith: ".widgetPull .ly-it,.widgetPull",
              placeholder: "item-highlight",
              start: function(event, ui) {
                $mxRowFrom = ui.item.parents(".ly-row");
                if ($(ui.item).attr("id")) {
                  _this.currWidgetId = "";
                  _this.currWidgetId = $(ui.item).attr("id");
                } else {
                  _this.currWidgetId = "";
                }
              },
              stop: function(event, ui) {
                maxHeight(ui.item);
                _this.bindId($(ui.item));
              }
            });
        }

        /**
         * 重新布局：在添加、删除列的时候执行
         *
         */
        function computeRow($content) {
          var $items = $(".ly-it", $content),
            $row = $(".ly-row", $content),
            _length = $items.length,
            _lyW = $(".ly", $content).width();
          if (_length > 3) {
            $items.css({
              width: _lyW / 3
            });
            $row.css({
              width: _lyW / 3 * $items.length
            });
          } else {
            $items.css({
              width: _lyW / $items.length
            });
            $row.css({
              width: _lyW
            });
          }
        }

        this.each(function() {
          var $layout = $(this),
            $ly = $(".ly", $layout),
            $row = $(".ly-row", $layout),
            $its = $(".ly-it", $layout),
            $addHandle = $(settings.addHandel, $layout),
            $dragHandle = $(settings.dragHandel, $layout),
            $delHandle = $(settings.delHandel, $layout),
            $delColHandle = $(settings.delColHandel, $layout),
            $editHandle = $(settings.editHandel, $layout),
            _index = -1;
          /**
             * 初始化
             * 1.为列添加选中事事件
             *
             */
          dropable($its);
          $ly.on("click", ".ly-it", function(e) {
            var $it = $(e.target);
            $(".ly-it.on", $row).removeClass("on");
            $delColHandle.removeClass("hd-unEdit");
            _index = $it.addClass("on").index();
          });
          //添加列
          $addHandle.on("click", function() {
            var $addIt = $('<div class="ly-it"></div>');
            $addIt.appendTo($row);
            $its = $(".ly-it", $row);
            computeRow($layout);
            dropable($addIt);
          });

          //删除列
          $delColHandle.on("click", function() {
            if ($delColHandle.hasClass("hd-unEdit") || _index < 0) {
              alert("请选择要被删除的咧");
            } else {
              $(".ly-it:eq(" + _index + ")", $row).remove();
              _index = -1;
              $delColHandle.addClass("hd-unEdit");
              computeRow($layout);
            }
          });
          //拖拽子表
          $dragHandle.on("click", function() {});
          //删除子表
          $delHandle.on("click", function() {});
          //编辑子表
          $editHandle.on("click", function() {});
        });
        return this;
      };
      //  $('.widget-layouts').mxly();
      //组件拖拽功能主要代码
      $(".widgetForm .item").draggable({
        connectToSortable: ".widgetPull,.widgetPull .ly-it",
        appendTo: ".com-layout",
        zIndex: 99,
        cursor: "move",
        cursorAt: { top: 18 },
        helper: "clone",
        start: function(e, t) {
          t.helper.addClass("drag").width(120);
        },
        drag: function(e, t) {},
        stop: function(e, t) {}
      });
      $(".widgetPull")
        .droppable({
          accept: ".widgetForm .item",
          drop: function(event, ui) {}
        })
        .sortable({
          placeholder: "item-highlight",
          connectWith: ".widgetPull .ly-it,.widgetPull",
          cursor: "move",
          stop: function(event, ui) {
              event.stopPropagation()
            var target = "." + ui.item.attr("data-target");
            if (target == ".form-layouts") {
              ui.item.mxly();
            }
            maxHeight(ui.item);
            // changeForm(target);
            _this.settingTarget = $(ui.item).attr('data-target')
            _this.bindId($(ui.item));
            _this.settingId($(ui.item).attr("id"));

            let params = {
                id: $(ui.item).attr("id"),
                title: $(ui.item).find('label').eq(0).text(),
                description: $(ui.item).find('.info').eq(0).text()
            }

            if (_this.settingTarget === 'form-formLine') {
                params.defaultVal = $(ui.item).find('input[type="text"]').val()
            }

            _this.saveSetting(params)
          },
          sort: function(event, ui) {},
          start: function(event, ui) {
            var target = "." + ui.item.attr("data-target");
            if ($defaultview.is(":visible")) {
              $defaultview.hide();
            }

            if ($(ui.item).attr("id")) {
              _this.currWidgetId = "";
              _this.currWidgetId = $(ui.item).attr("id");
            } else {
              _this.currWidgetId = "";
            }
          }
        });
    })();
  },

  computed: {
    ...mapState(["currSettingId", "setting"])
  },

  methods: {
    ...mapMutations(["SET_CURR_SETTING_ID", "SET_SETTING_INFO"]),

    /* 给每个组件添加id */
    bindId($dom) {
      if (!this.currWidgetId) {
        $dom.attr("id", this.widgetId);
        this.widgetId++;
      } else {
        $dom.attr("id", this.currWidgetId);
      }
    },

    /* 保存当前设置信息 */
    saveSetting(params) {
        this.SET_SETTING_INFO(params)
    },

    /* 设置当前编辑的组件id */
    settingId(id) {
      this.SET_CURR_SETTING_ID(id);
    }
  },

  watch: {
    'setting': {
        handler() {
            $('#' + this.currSettingId).find('label').eq(0).text(this.setting[this.currSettingId].title) // 标题
            $('#' + this.currSettingId).find('.info').eq(0).text(this.setting[this.currSettingId].description) // 描述
            if (this.settingTarget === 'form-formLine') {
                $('#' + this.currSettingId).find('input[type="text"]').eq(0).val(this.setting[this.currSettingId].defaultVal) // 默认值
            }
        },
        deep: true
    }
  }
};
</script>
